package com.wsj.aop;

import com.wsj.services.impl.ProxyTestImpl;
import com.wsj.services.ProxyTest;
import java.lang.reflect.Method;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

/**
 * description:cglib动态代理
 *
 * @author yang
 * @date 2019/2/20 9:46
 */
public class CglibProxy implements MethodInterceptor {

  private Object target;

  private CglibProxy(Object target) {
    this.target = target;
  }

  @Override
  public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
    System.err.println("CglibProxy...before..." + method);
    Object result = methodProxy.invokeSuper(o, objects);
    System.err.println("CglibProxy...after..." + method);
    return result;
  }

  private Object getProxyObject() {
    Enhancer enhancer = new Enhancer();
    //设置父类
    enhancer.setSuperclass(this.target.getClass());
    //设置回调，再调用父类方法时，回调this.intercept()
    enhancer.setCallback(this);
    //创建代理对象
    return enhancer.create();
  }

  public static void main(String[] args) {
    ProxyTestImpl proxyTarget = new ProxyTestImpl();
    CglibProxy cglibProxy = new CglibProxy(proxyTarget);
    ProxyTest proxy = (ProxyTest) cglibProxy.getProxyObject();
    proxy.print();
    System.out.println(proxy);
  }
}
